package com.cn.kehong.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cn.kehong.api.IEnergyService;
import com.cn.kehong.conf.Config;
import com.cn.kehong.dao.*;
import com.cn.kehong.domain.*;
import com.cn.kehong.utils.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@EnableScheduling
@Service
public class EnergyServiceImpl implements IEnergyService {

  @Autowired private EnergyMapper energyMapper;
    @Autowired
    private Config config;
@Override
public Map<String, Object> getEnergyByWorkshop(QueryForm queryForm) throws Exception {
        LocalDate now = LocalDate.now();
        // 获取当前年份当前年
        int currentYear = now.getYear();
        // 获取上一年份上年
        int lastYear = currentYear - 1;
        // 获取当前月份（1-12）当前月
        int currentMonth = now.getMonthValue();
        // 获取昨天的日期
        LocalDate yesterday = now.minusDays(1);
        String yesterdayDay = String.valueOf(yesterday.getDayOfMonth());
        // 获取今天的日
         String today = String.valueOf(now.getDayOfMonth());

    Map<String, Object> result = new HashMap<>();
    List<Map<String, Object>> workshopsList = new ArrayList<>();
    Set<String> processedWorkshops = new HashSet<>();

    // 查询所有的厂房
    List<Energy> workshops = energyMapper.getWorkshop();
    // 查询所有的能源类型
    List<Energy> energyTypes = energyMapper.getEnergyType();

    // 默认的能源类型
    List<String> defaultEnergyTypes = Arrays.asList("水", "电", "气");

    for (Energy workshopEnergy : workshops) {
        if (processedWorkshops.contains(workshopEnergy.getWorkshop())) {
            continue;
        }

        Map<String, Object> workshopInfo = new HashMap<>();
        List<Map<String, Object>> energyDetails = new ArrayList<>();
        processedWorkshops.add(workshopEnergy.getWorkshop());

        // 初始化默认能源类型数据
        Map<String, Map<String, Object>> defaultEnergyMap = new HashMap<>();
        for (String energyType : defaultEnergyTypes) {
            Map<String, Object> defaultEnergyInfo = new HashMap<>();
            defaultEnergyInfo.put("type", energyType);
            if(energyType.equals("水")){
                defaultEnergyInfo.put("unit", "t");
            }else if (energyType.equals("电")){
                defaultEnergyInfo.put("unit", "万度");
            }else if (energyType.equals("气")){
                defaultEnergyInfo.put("unit", "m³");
            }
            defaultEnergyInfo.put("lastYear", 0.0);
            defaultEnergyInfo.put("currentYear", 0.0);
            defaultEnergyInfo.put("currentMonth", 0.0);
            defaultEnergyInfo.put("today", 0.0);
            defaultEnergyInfo.put("yestoday", 0);
            defaultEnergyMap.put(energyType, defaultEnergyInfo);
        }

        for (Energy energyType : energyTypes) {
            List<Energy> energyListDetails = energyMapper.selectByCreateTime(workshopEnergy.getWorkshop(), energyType.getEnergyType());

            for (Energy e : energyListDetails) {
                String energyTypeStr = getEnergyTypeString(e.getEnergyType());
                Map<String, Object> energyInfo = defaultEnergyMap.get(energyTypeStr);

                if (energyInfo != null) {
                    // 更新默认数据
                    energyInfo.put("unit", e.getUnit());
                    energyInfo.put("lastYear", energyMapper.getLastYear(workshopEnergy.getWorkshop(), energyType.getEnergyType(), String.valueOf(lastYear)));
                    energyInfo.put("currentYear", energyMapper.getCurrentYear(workshopEnergy.getWorkshop(), energyType.getEnergyType(), String.valueOf(currentYear)));
                    energyInfo.put("currentMonth", energyMapper.getCurrentMonth(workshopEnergy.getWorkshop(), energyType.getEnergyType(), String.valueOf(currentMonth)));

                    List<Energy> yestodays = energyMapper.getYestoday(workshopEnergy.getWorkshop(), energyType.getEnergyType(), String.valueOf(currentYear), String.valueOf(currentMonth), yesterdayDay);
                    List<Energy> todays = energyMapper.getToday(workshopEnergy.getWorkshop(), energyType.getEnergyType(), String.valueOf(currentYear), String.valueOf(currentMonth),today);
                    energyInfo.put("yestoday", yestodays.size() > 0 ? yestodays.get(0).getToday() : 0);
                    energyInfo.put("today", todays.size() > 0 ? todays.get(0).getToday() : 0);
                }
            }
        }

        energyDetails.addAll(defaultEnergyMap.values());

        if (!energyDetails.isEmpty()) {
            workshopInfo.put("workshop", workshopEnergy.getWorkshop() + "#");
            workshopInfo.put("list", energyDetails);
            workshopsList.add(workshopInfo);
        }
    }

    Map<String, Object> resultData = new HashMap<>();
    resultData.put("workshops", workshopsList);

    result.put("result", resultData);
    result.put("errorCode", "");
    result.put("status", 0);
    result.put("success", true);

    return result;
}

@Override
public Map<String, Object> getEnergyByType(QueryForm queryForm) throws Exception {
    LocalDate now = LocalDate.now();
    int currentYear = now.getYear();
    int lastYear = currentYear - 1;
    int currentMonth = now.getMonthValue();
    LocalDate yesterday = now.minusDays(1);
    String yesterdayDay = String.valueOf(yesterday.getDayOfMonth());
    String today = String.valueOf(now.getDayOfMonth());
    Map<String, Object> result = new HashMap<>();
    List<Map<String, Object>> energyTypesList = new ArrayList<>();

    // 查询所有的厂房
    List<Energy> workshops = energyMapper.getWorkshop();
    // 查询所有的能源类型
    List<Energy> energyTypes = energyMapper.getEnergyType();

    for (Energy energyType : energyTypes) {
        Map<String, Object> energyTypeInfo = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        BigDecimal sumLastYear = BigDecimal.ZERO;
        BigDecimal sumThisYear = BigDecimal.ZERO;
        BigDecimal sumThisMonth = BigDecimal.ZERO;
        BigDecimal sumYesterday = BigDecimal.ZERO;
        BigDecimal sumToday = BigDecimal.ZERO;

        // 初始化每个厂房的默认值
        Map<String, Map<String, Object>> defaultWorkshopMap = new HashMap<>();
        for (Energy workshopEnergy : workshops) {
            Map<String, Object> defaultWorkshopData = new HashMap<>();
            defaultWorkshopData.put("workshop", workshopEnergy.getWorkshop() + "#");
            defaultWorkshopData.put("lastYear", 0.0);
            defaultWorkshopData.put("currentYear", 0.0);
            defaultWorkshopData.put("currentMonth", 0.0);
            defaultWorkshopData.put("yestoday", 0);
            defaultWorkshopData.put("today", 0.0);
            defaultWorkshopMap.put(workshopEnergy.getWorkshop(), defaultWorkshopData);
        }

        for (Energy workshopEnergy : workshops) {
            List<Energy> energyListDetails = energyMapper.selectByCreateTime(workshopEnergy.getWorkshop(), energyType.getEnergyType());
            for (Energy e : energyListDetails) {
                Map<String, Object> workshopData = defaultWorkshopMap.get(workshopEnergy.getWorkshop());

                if (workshopData != null) {
                    // 查询各时间段的合计
                    BigDecimal lastYearSum = energyMapper.getLastYear(workshopEnergy.getWorkshop(), energyType.getEnergyType(), String.valueOf(lastYear));
                    BigDecimal currentYearSum = energyMapper.getCurrentYear(workshopEnergy.getWorkshop(), energyType.getEnergyType(), String.valueOf(currentYear));
                    BigDecimal currentMonthSum = energyMapper.getCurrentMonth(workshopEnergy.getWorkshop(), energyType.getEnergyType(), String.valueOf(currentMonth));
                    List<Energy> yestodays = energyMapper.getYestoday(workshopEnergy.getWorkshop(), energyType.getEnergyType(), String.valueOf(currentYear), String.valueOf(currentMonth), yesterdayDay);
                    List<Energy> todays = energyMapper.getToday(workshopEnergy.getWorkshop(), energyType.getEnergyType(), String.valueOf(currentYear), String.valueOf(currentMonth),today);

                    // 更新默认值为实际数据
                    workshopData.put("lastYear", lastYearSum.doubleValue());
                    workshopData.put("currentYear", currentYearSum.doubleValue());
                    workshopData.put("currentMonth", currentMonthSum.doubleValue());
//                    workshopData.put("today", e.getToday());
                    workshopData.put("today", todays.size() > 0 ? todays.get(0).getToday() : 0);
                    workshopData.put("yestoday", yestodays.size() > 0 ? yestodays.get(0).getToday() : 0);

                    sumLastYear = sumLastYear.add(lastYearSum);
                    sumThisYear = sumThisYear.add(currentYearSum);
                    sumThisMonth = sumThisMonth.add(currentMonthSum);
                    sumYesterday = sumYesterday.add(yestodays.size() > 0 ? convertToBigDecimal(yestodays.get(0).getToday()) : BigDecimal.ZERO);
                    sumToday = sumToday.add(todays.size() > 0 ? convertToBigDecimal(todays.get(0).getToday()) : BigDecimal.ZERO);
//                    sumToday = sumToday.add(convertToBigDecimal(e.getToday()));
                }
            }
        }

        list.addAll(defaultWorkshopMap.values());

        // 添加合计数据
        Map<String, Object> totalData = new HashMap<>();
        totalData.put("workshop", "合计");
        totalData.put("lastYear", String.format("%.2f", sumLastYear));
        totalData.put("currentYear", String.format("%.2f", sumThisYear));
        totalData.put("currentMonth", String.format("%.2f", sumThisMonth));
        totalData.put("yestoday", String.format("%.2f", sumYesterday));
        totalData.put("today", String.format("%.2f", sumToday));
        list.add(totalData);

        energyTypeInfo.put("type", getEnergyTypeString(energyType.getEnergyType()));
        energyTypeInfo.put("unit", energyType.getUnit());
        energyTypeInfo.put("list", list);
        energyTypesList.add(energyTypeInfo);
    }

    result.put("energyTypes", energyTypesList);
    return result;
}

    public Map<String, Object> getEnergyByTrend(QueryForm queryForm) throws Exception {
        String currentYear= String.valueOf(queryForm.getStartYear());
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> workshopsList = new ArrayList<>();

        // 查询所有的能源类型
        List<Energy> energyTypes = energyMapper.getEnergyType();

        for (Energy energyType : energyTypes) {
            List<BigDecimal> monthlyValues = new ArrayList<>();
            BigDecimal sumMonth = BigDecimal.ZERO;

            for (int i = 1; i <= 12; i++) {
                // 查询每个月的能源数据
                //可能需要修改，现在是根据每天的最新时间来分组排序的
                List<Energy> energyListDetails = energyMapper.selectByTypeAndi(energyType.getEnergyType(), currentYear, i);
                BigDecimal monthlySum = BigDecimal.ZERO;

                // 计算每月的总值
                for (Energy energy : energyListDetails) {
                    monthlySum = monthlySum.add(convertToBigDecimal(energy.getToday()));
                }
                monthlyValues.add(monthlySum.setScale(2, RoundingMode.HALF_UP));
                // 累加全年总值
                sumMonth = sumMonth.add(monthlySum);
            }

            // 添加合计数据
            Map<String, Object> totalData = new HashMap<>();
            totalData.put("type", getEnergyTypeString(energyType.getEnergyType()));
            totalData.put("unit", energyType.getUnit());
            totalData.put("list",monthlyValues);
            totalData.put("total", String.format("%.2f", sumMonth));  // 格式化为两位小数

            // 将每种能源类型的数据添加到结果列表中
            workshopsList.add(totalData);
        }

        result.put("workshops", workshopsList);
        return result;
    }

@Override
public Map<String, Object> getEnergyData(QueryForm queryForm) throws Exception {
    // 将数据添加到结果 Map 中
    Map<String, Object> resultMap = new HashMap<>();
    // 初始化存储最大和最小记录
    BigDecimal maxWaterToday = BigDecimal.ZERO;
    BigDecimal minWaterToday = BigDecimal.valueOf(Double.MAX_VALUE);
    List<String> maxWaterDates = new ArrayList<>();
    List<String> minWaterDates = new ArrayList<>();

    BigDecimal maxElectricityToday = BigDecimal.ZERO;
    BigDecimal minElectricityToday = BigDecimal.valueOf(Double.MAX_VALUE);
    List<String> maxElectricityDates = new ArrayList<>();
    List<String> minElectricityDates = new ArrayList<>();

    BigDecimal maxGasToday = BigDecimal.ZERO;
    BigDecimal minGasToday = BigDecimal.valueOf(Double.MAX_VALUE);
    List<String> maxGasDates = new ArrayList<>();
    List<String> minGasDates = new ArrayList<>();

    BigDecimal waterSum = BigDecimal.ZERO;
    BigDecimal electricitySum = BigDecimal.ZERO;
    BigDecimal gasSum = BigDecimal.ZERO;

    if (StringUtils.isNotEmpty(queryForm.getEnergyType())) {
        String[] energyTypes = queryForm.getEnergyType().split(",");
        List<String> list = Arrays.asList(energyTypes);
        List<Energy> energyList = energyMapper.selectEnergyData(list, queryForm.getWorkshop(), queryForm.getStartTime(), queryForm.getEndTime());

        for (Energy energy : energyList) {
            BigDecimal todayValue = convertToBigDecimal(energy.getToday());
            String recordDate = energy.getRecordMonth() + "-" + energy.getRecordDay(); // 拼接成 MM-DD 格式

            switch (energy.getEnergyType()) {
                case "0":
                    waterSum = waterSum.add(todayValue);
                    if (todayValue.compareTo(maxWaterToday) > 0) {
                        maxWaterToday = todayValue;
                        maxWaterDates.clear();
                        maxWaterDates.add(recordDate);
                    } else if (todayValue.compareTo(maxWaterToday) == 0) {
                        maxWaterDates.add(recordDate);
                    }
                    if (todayValue.compareTo(minWaterToday) < 0) {
                        minWaterToday = todayValue;
                        minWaterDates.clear();
                        minWaterDates.add(recordDate);
                    } else if (todayValue.compareTo(minWaterToday) == 0) {
                        minWaterDates.add(recordDate);
                    }
                    break;
                case "1":
                    electricitySum = electricitySum.add(todayValue);
                    if (todayValue.compareTo(maxElectricityToday) > 0) {
                        maxElectricityToday = todayValue;
                        maxElectricityDates.clear();
                        maxElectricityDates.add(recordDate);
                    } else if (todayValue.compareTo(maxElectricityToday) == 0) {
                        maxElectricityDates.add(recordDate);
                    }
                    if (todayValue.compareTo(minElectricityToday) < 0) {
                        minElectricityToday = todayValue;
                        minElectricityDates.clear();
                        minElectricityDates.add(recordDate);
                    } else if (todayValue.compareTo(minElectricityToday) == 0) {
                        minElectricityDates.add(recordDate);
                    }
                    break;
                case "2":
                    gasSum = gasSum.add(todayValue);
                    if (todayValue.compareTo(maxGasToday) > 0) {
                        maxGasToday = todayValue;
                        maxGasDates.clear();
                        maxGasDates.add(recordDate);
                    } else if (todayValue.compareTo(maxGasToday) == 0) {
                        maxGasDates.add(recordDate);
                    }
                    if (todayValue.compareTo(minGasToday) < 0) {
                        minGasToday = todayValue;
                        minGasDates.clear();
                        minGasDates.add(recordDate);
                    } else if (todayValue.compareTo(minGasToday) == 0) {
                        minGasDates.add(recordDate);
                    }
                    break;
            }
        }
        Map<String, Object> waterData = new HashMap<>();
        waterData.put("type", "水");
        waterData.put("unit", "t");
        waterData.put("total", String.format("%.3f", waterSum));
        waterData.put("maxDate", String.join(",", maxWaterDates));
        waterData.put("minDate", String.join(",", minWaterDates));

        Map<String, Object> electricityData = new HashMap<>();
        electricityData.put("type", "电");
        electricityData.put("unit", "万度");
        electricityData.put("total", String.format("%.3f", electricitySum));
        electricityData.put("maxDate", String.join(",", maxElectricityDates));
        electricityData.put("minDate", String.join(",", minElectricityDates));

        Map<String, Object> gasData = new HashMap<>();
        gasData.put("type", "气");
        gasData.put("unit", "m³");
        gasData.put("total", String.format("%.3f", gasSum));
        gasData.put("maxDate", String.join(",", maxGasDates));
        gasData.put("minDate", String.join(",", minGasDates));

        resultMap.put("waterData", waterData);
        resultMap.put("electricityData", electricityData);
        resultMap.put("gasData", gasData);

    }


    return resultMap;
}

    @Override
    public void exportEnergy(QueryForm queryForm, HttpServletResponse response) throws Exception {
        String delimiter = "园区";
        BigDecimal sumHj = BigDecimal.ZERO;
        Map<String,Object> result = Maps.newHashMap();

        List<Energy> dataList = energyMapper.getDataList(queryForm);
        for (Energy energy : dataList) {
            try {
                String todayValue = energy.getToday();
                if (todayValue != null && !todayValue.isEmpty()) {
                    BigDecimal decimal = new BigDecimal(todayValue);
                    sumHj = sumHj.add(decimal);  // 正确累加
                }
            } catch (NumberFormatException e) {
                System.err.println("=====: " + energy.getToday());
            }
            // 设置区域和车间名称
            String[] parts = energy.getWorkshop().split(delimiter, 2);
            energy.setArea(parts[0] + delimiter);
            energy.setWorkshop(parts.length > 1 ? parts[1] : "");
            energy.setEnergyType(getEnergyTypeString(energy.getEnergyType()));
        }
        if (!dataList.isEmpty()) {
            dataList.get(0).setHjToday(String.valueOf(sumHj));
        }
        String endTime = queryForm.getEndTime();
        if (endTime != null && !endTime.isEmpty()) {
            endTime = endTime.split(" ")[0]; // 切割字符串，保留日期部分
        }
        result.put("startTime", queryForm.getStartTime());
        result.put("endTime", endTime);
        result.put("workshop", queryForm.getWorkshop());
        result.put("queryTime", queryForm.getQueryTime());
        result.put("queryName", queryForm.getQueryName());
        result.put("sumHj", sumHj);
            result.put("energy", dataList);
            String fileName = CommonUtil.generateRandomNum("ny-")+".xlsx";
            String filePath = config.filePath+fileName;
            String nameStr=queryForm.getStartTime()+"-"+endTime+" 能源能耗_"+getEnergyTypeString(queryForm.getEnergyType())+".xlsx";
            TemplateExcelUtils.downLoadExcel(filePath,nameStr,result,"nyxx.xlsx", response);
    }



    private String getEnergyTypeString(String code) {
    switch (code) {
      case "0":
        return "水";
      case "1":
        return "电";
      case "2":
        return "气";
      default:
        return "未知";
    }
  }


    private BigDecimal convertToBigDecimal(String value) {
        try {
            return new BigDecimal(value);
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
    }



    public Map<String, Object> getListByElectricity(QueryForm queryForm) throws Exception {
        // 分隔符
        String delimiter = "园区";
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int lastYear = currentYear - 1;
        int currentMonth = now.getMonthValue();
        LocalDate yesterday = now.minusDays(1);
        String yesterdayDay = String.valueOf(yesterday.getDayOfMonth());

        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> energyTypesList = new ArrayList<>();
        Map<String, List<Map<String, Object>>> workShopMap = new HashMap<>();
        Map<String, BigDecimal> workShopLastYearSum = new HashMap<>();
        Map<String, BigDecimal> workShopCurrentYearSum = new HashMap<>();
        List<Energy> workshops = energyMapper.getElectricityType("1");
        for (Energy workshopEnergy : workshops) {
            BigDecimal sumLastYear = BigDecimal.ZERO;
            BigDecimal sumThisYear = BigDecimal.ZERO;
            BigDecimal sumYesterday = BigDecimal.ZERO;
            BigDecimal tenThousand = new BigDecimal("10000");

            BigDecimal lastYearSum = energyMapper.getLastYear(workshopEnergy.getWorkshop(), "1", String.valueOf(lastYear));
            BigDecimal currentYearSum = energyMapper.getCurrentYear(workshopEnergy.getWorkshop(), "1", String.valueOf(currentYear));
            List<Energy> yestodays = energyMapper.getYestoday(workshopEnergy.getWorkshop(), "1", String.valueOf(currentYear), String.valueOf(currentMonth), yesterdayDay);

            sumLastYear = sumLastYear.add(lastYearSum);
            sumThisYear = sumThisYear.add(currentYearSum);
            sumYesterday = sumYesterday.add(yestodays.size() > 0 ? convertToBigDecimal(yestodays.get(0).getToday()) : BigDecimal.ZERO);
            BigDecimal sumLastYearDivided = sumLastYear.divide(tenThousand, 3, RoundingMode.HALF_UP);
            BigDecimal sumThisYearDivided = sumThisYear.divide(tenThousand, 3, RoundingMode.HALF_UP);
//            BigDecimal sumYesterdayDivided = sumYesterday.divide(tenThousand, 3, RoundingMode.HALF_UP);
            Map<String, Object> totalData = new HashMap<>();
            totalData.put("area", workshopEnergy.getWorkshop().split(delimiter, 2)[1] );
            totalData.put("lastYear", String.format("%.3f", sumLastYearDivided));
            totalData.put("currentYear", String.format("%.3f", sumThisYearDivided));
            totalData.put("yestoday", String.valueOf(sumYesterday));

            // 使用 workShopMap 进行分组
            String workShop = workshopEnergy.getWorkshop().split(delimiter, 2)[0]+ delimiter;
            if (!workShopMap.containsKey(workShop)) {
                workShopMap.put(workShop, new ArrayList<>());
                workShopLastYearSum.put(workShop, BigDecimal.ZERO);
                workShopCurrentYearSum.put(workShop, BigDecimal.ZERO);
            }
            workShopMap.get(workShop).add(totalData);
        }

        // 构建最终的结果列表
        for (Map.Entry<String, List<Map<String, Object>>> entry : workShopMap.entrySet()) {
            Map<String, Object> workShopData = new HashMap<>();
            workShopData.put("workShop", entry.getKey());
            workShopData.put("list", entry.getValue());
            energyTypesList.add(workShopData);
        }

        result.put("energyTypes", energyTypesList);
        return result;
    }

    public List<Energy> getListByWater(QueryForm queryForm) throws Exception {
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int lastYear = currentYear - 1;
        int currentMonth = now.getMonthValue();
        LocalDate yesterday = now.minusDays(1);
        String yesterdayDay = String.valueOf(yesterday.getDayOfMonth());

        // 获取所有能源数据
        EnergyExample example = new EnergyExample();
        example.createCriteria().andEnergyTypeEqualTo("0");
        List<Energy> energyList = energyMapper.selectByExample(example);

        // 使用 Map 进行合并
        Map<String, Energy> energyMap = new HashMap<>();

        for (Energy energy : energyList) {
            String workshop = energy.getWorkshop();
            BigDecimal tenThousand = new BigDecimal("10000");

            BigDecimal lastYearSum = energyMapper.getLastYear(workshop, "0", String.valueOf(lastYear));
            BigDecimal currentYearSum = energyMapper.getCurrentYear(workshop, "0", String.valueOf(currentYear));
            List<Energy> yestodays = energyMapper.getYestoday(workshop, "0", String.valueOf(currentYear), String.valueOf(currentMonth), yesterdayDay);

            BigDecimal sumLastYear = lastYearSum != null ? lastYearSum : BigDecimal.ZERO;
            BigDecimal sumThisYear = currentYearSum != null ? currentYearSum : BigDecimal.ZERO;
            BigDecimal sumYesterday = yestodays.size() > 0 ? convertToBigDecimal(yestodays.get(0).getToday()) : BigDecimal.ZERO;

            BigDecimal sumLastYearDivided = sumLastYear.divide(tenThousand, 3, RoundingMode.HALF_UP);
            BigDecimal sumThisYearDivided = sumThisYear.divide(tenThousand, 3, RoundingMode.HALF_UP);
//            BigDecimal sumYesterdayDivided = sumYesterday.divide(tenThousand, 3, RoundingMode.HALF_UP);

            // 合并数据
            if (!energyMap.containsKey(workshop)) {
                Energy mergedEnergy = new Energy();
                mergedEnergy.setWorkshop(workshop);
                mergedEnergy.setSumLastYear(sumLastYearDivided.toString());
                mergedEnergy.setThisYear(sumThisYearDivided.toString());
                mergedEnergy.setYesterday(sumYesterday.toString());
                energyMap.put(workshop, mergedEnergy);
            } else {
                Energy existingEnergy = energyMap.get(workshop);
                BigDecimal existingLastYear = new BigDecimal(existingEnergy.getSumLastYear());
                BigDecimal existingThisYear = new BigDecimal(existingEnergy.getThisYear());
                BigDecimal existingYesterday = new BigDecimal(existingEnergy.getYesterday());

                existingEnergy.setSumLastYear(existingLastYear.add(sumLastYearDivided).toString());
                existingEnergy.setThisYear(existingThisYear.add(sumThisYearDivided).toString());
                existingEnergy.setYesterday(existingYesterday.add(sumYesterday).toString());
            }
        }

        // 返回合并后的结果
        return new ArrayList<>(energyMap.values());
    }

    @Override
    public List<Energy> getListByGas(QueryForm queryForm) throws Exception {
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int lastYear = currentYear - 1;
        int currentMonth = now.getMonthValue();
        LocalDate yesterday = now.minusDays(1);
        String yesterdayDay = String.valueOf(yesterday.getDayOfMonth());

        // 获取所有能源数据
        EnergyExample example = new EnergyExample();
        example.createCriteria().andEnergyTypeEqualTo("2");
        List<Energy> energyList = energyMapper.selectByExample(example);

        // 使用 Map 进行合并
        Map<String, Energy> energyMap = new HashMap<>();

        for (Energy energy : energyList) {
            String workshop = energy.getWorkshop();
            BigDecimal tenThousand = new BigDecimal("10000");

            BigDecimal lastYearSum = energyMapper.getLastYear(workshop, "2", String.valueOf(lastYear));
            BigDecimal currentYearSum = energyMapper.getCurrentYear(workshop, "2", String.valueOf(currentYear));
            List<Energy> yestodays = energyMapper.getYestoday(workshop, "2", String.valueOf(currentYear), String.valueOf(currentMonth), yesterdayDay);

            BigDecimal sumLastYear = lastYearSum != null ? lastYearSum : BigDecimal.ZERO;
            BigDecimal sumThisYear = currentYearSum != null ? currentYearSum : BigDecimal.ZERO;
            BigDecimal sumYesterday = yestodays.size() > 0 ? convertToBigDecimal(yestodays.get(0).getToday()) : BigDecimal.ZERO;

            BigDecimal sumLastYearDivided = sumLastYear.divide(tenThousand, 3, RoundingMode.HALF_UP);
            BigDecimal sumThisYearDivided = sumThisYear.divide(tenThousand, 3, RoundingMode.HALF_UP);
//            BigDecimal sumYesterdayDivided = sumYesterday.divide(tenThousand, 3, RoundingMode.HALF_UP);

            // 合并数据
            if (!energyMap.containsKey(workshop)) {
                Energy mergedEnergy = new Energy();
                mergedEnergy.setWorkshop(workshop);
                mergedEnergy.setSumLastYear(sumLastYearDivided.toString());
                mergedEnergy.setThisYear(sumThisYearDivided.toString());
                mergedEnergy.setYesterday(sumYesterday.toString());
                energyMap.put(workshop, mergedEnergy);
            } else {
                Energy existingEnergy = energyMap.get(workshop);
                BigDecimal existingLastYear = new BigDecimal(existingEnergy.getSumLastYear());
                BigDecimal existingThisYear = new BigDecimal(existingEnergy.getThisYear());
                BigDecimal existingYesterday = new BigDecimal(existingEnergy.getYesterday());

                existingEnergy.setSumLastYear(existingLastYear.add(sumLastYearDivided).toString());
                existingEnergy.setThisYear(existingThisYear.add(sumThisYearDivided).toString());
                existingEnergy.setYesterday(existingYesterday.add(sumYesterday).toString());
            }
        }

        // 返回合并后的结果
        return new ArrayList<>(energyMap.values());
    }

    @Override
    public List<Energy> getDataList(QueryForm queryForm) throws Exception {
        String delimiter = "园区";
        BigDecimal sumHj = BigDecimal.ZERO;
        List<Energy> dataList = energyMapper.getDataList(queryForm);
        for (Energy energy : dataList) {
            try {
                String todayValue = energy.getToday();
                if (todayValue != null && !todayValue.isEmpty()) {
                    BigDecimal decimal = new BigDecimal(todayValue);
                    sumHj = sumHj.add(decimal);  // 正确累加
                }
            } catch (NumberFormatException e) {
                System.err.println("=====: " + energy.getToday());
            }
            // 设置区域和车间名称
            String[] parts = energy.getWorkshop().split(delimiter, 2);
            energy.setArea(parts[0] + delimiter);
            energy.setWorkshop(parts.length > 1 ? parts[1] : "");
            energy.setEnergyType(getEnergyTypeString(energy.getEnergyType()));
        }
        if (!dataList.isEmpty()) {
            dataList.get(0).setHjToday(String.valueOf(sumHj));
        }
        return dataList;
    }

    @Override
    public List<Energy> getListByLight(QueryForm queryForm) throws Exception {
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int lastYear = currentYear - 1;
        int currentMonth = now.getMonthValue();
        LocalDate yesterday = now.minusDays(1);
        String yesterdayDay = String.valueOf(yesterday.getDayOfMonth());

        // 获取所有能源数据
        EnergyExample example = new EnergyExample();
        example.createCriteria().andEnergyTypeEqualTo("3");
        List<Energy> energyList = energyMapper.selectByExample(example);

        // 使用 Map 进行合并
        Map<String, Energy> energyMap = new HashMap<>();

        for (Energy energy : energyList) {
            String workshop = energy.getWorkshop();
            BigDecimal tenThousand = new BigDecimal("10000");

            BigDecimal lastYearSum = energyMapper.getLastYear(workshop, "3", String.valueOf(lastYear));
            BigDecimal currentYearSum = energyMapper.getCurrentYear(workshop, "3", String.valueOf(currentYear));
            List<Energy> yestodays = energyMapper.getYestoday(workshop, "3", String.valueOf(currentYear), String.valueOf(currentMonth), yesterdayDay);

            BigDecimal sumLastYear = lastYearSum != null ? lastYearSum : BigDecimal.ZERO;
            BigDecimal sumThisYear = currentYearSum != null ? currentYearSum : BigDecimal.ZERO;
            BigDecimal sumYesterday = yestodays.size() > 0 ? convertToBigDecimal(yestodays.get(0).getToday()) : BigDecimal.ZERO;

            BigDecimal sumLastYearDivided = sumLastYear.divide(tenThousand, 3, RoundingMode.HALF_UP);
            BigDecimal sumThisYearDivided = sumThisYear.divide(tenThousand, 3, RoundingMode.HALF_UP);
            BigDecimal sumYesterdayDivided = sumYesterday.divide(tenThousand, 3, RoundingMode.HALF_UP);

            // 合并数据
            if (!energyMap.containsKey(workshop)) {
                Energy mergedEnergy = new Energy();
                mergedEnergy.setWorkshop(workshop);
                mergedEnergy.setSumLastYear(sumLastYearDivided.toString());
                mergedEnergy.setThisYear(sumThisYearDivided.toString());
                mergedEnergy.setYesterday(sumYesterdayDivided.toString());
                energyMap.put(workshop, mergedEnergy);
            } else {
                Energy existingEnergy = energyMap.get(workshop);
                BigDecimal existingLastYear = new BigDecimal(existingEnergy.getSumLastYear());
                BigDecimal existingThisYear = new BigDecimal(existingEnergy.getThisYear());
                BigDecimal existingYesterday = new BigDecimal(existingEnergy.getYesterday());

                existingEnergy.setSumLastYear(existingLastYear.add(sumLastYearDivided).toString());
                existingEnergy.setThisYear(existingThisYear.add(sumThisYearDivided).toString());
                existingEnergy.setYesterday(existingYesterday.add(sumYesterdayDivided).toString());
            }
        }

        // 返回合并后的结果
        return new ArrayList<>(energyMap.values());
    }

    @Override
    public Map<String, Object> getDataListByKb(QueryForm queryForm) throws Exception {
        Map<String, Object> map = new HashMap<>();
        BigDecimal sumYear = BigDecimal.ZERO;
        BigDecimal sumMonth = BigDecimal.ZERO;
        BigDecimal sumYesterday = BigDecimal.ZERO;
        BigDecimal tenThousand = new BigDecimal("10000");
        // 获取本年的开始和结束时间
        LocalDate startOfYear = LocalDate.now().withDayOfYear(1).minusDays(1);
        LocalDateTime startOfYearDateTime = startOfYear.atStartOfDay();
        LocalDateTime endOfYearDateTime = LocalDate.now().atTime(23, 59, 59);

        // 获取本月的开始和结束时间
        LocalDate startOfMonth = LocalDate.now().withDayOfMonth(1).minusDays(1);
        LocalDateTime startOfMonthDateTime = startOfMonth.atStartOfDay();
        LocalDateTime endOfMonthDateTime = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).atTime(23, 59, 59);

        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        LocalDateTime startYesterday = yesterday.atStartOfDay();
        LocalDateTime endYesterday = yesterday.plusDays(1).atStartOfDay();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //水
        if (queryForm.getEnergyType().equals("0")){
            queryForm.setEnergyType("0");
            queryForm.setStartTime(formatter.format(startOfYearDateTime));
            queryForm.setEndTime(formatter.format(endOfYearDateTime));
            List<Energy> yearDataList = energyMapper.getDataList(queryForm);
            sumYear = sumDataList(yearDataList);

            // 本月数据总和
            queryForm.setStartTime(formatter.format(startOfMonthDateTime));
            queryForm.setEndTime(formatter.format(endOfMonthDateTime));
            List<Energy> monthDataList = energyMapper.getDataList(queryForm);
            sumMonth = sumDataList(monthDataList);

            // 昨天数据总和
            queryForm.setStartTime(formatter.format(startYesterday));
            queryForm.setEndTime(formatter.format(endYesterday));
            List<Energy> yesterdayDataList = energyMapper.getDataList(queryForm);
            sumYesterday = sumDataList(yesterdayDataList);
            map.put("waterSumYear", sumYear);
            map.put("waterSumMonth", sumMonth);
            map.put("waterSumYesterday", sumYesterday);
        }else if (queryForm.getEnergyType().equals("1")){
            queryForm.setEnergyType("1");
            queryForm.setStartTime(formatter.format(startOfYearDateTime));
            queryForm.setEndTime(formatter.format(endOfYearDateTime));
            List<Energy> yearDataList = energyMapper.getDataList(queryForm);
            sumYear = sumDataList(yearDataList);

            // 本月数据总和
            queryForm.setStartTime(formatter.format(startOfMonthDateTime));
            queryForm.setEndTime(formatter.format(endOfMonthDateTime));
            List<Energy> monthDataList = energyMapper.getDataList(queryForm);
            sumMonth = sumDataList(monthDataList);

            // 昨天数据总和
            queryForm.setStartTime(formatter.format(startYesterday));
            queryForm.setEndTime(formatter.format(endYesterday));
            List<Energy> yesterdayDataList = energyMapper.getDataList(queryForm);
            sumYesterday = sumDataList(yesterdayDataList);
            map.put("electricitySumYear", sumYear.divide(tenThousand, 3, BigDecimal.ROUND_HALF_UP));
            map.put("electricitySumMonth",sumMonth.divide(tenThousand, 3, BigDecimal.ROUND_HALF_UP));
            map.put("electricitySumYesterday",sumYesterday.divide(tenThousand, 3, BigDecimal.ROUND_HALF_UP));
        }else if (queryForm.getEnergyType().equals("2")){
            queryForm.setEnergyType("2");
            queryForm.setStartTime(formatter.format(startOfYearDateTime));
            queryForm.setEndTime(formatter.format(endOfYearDateTime));
            List<Energy> yearDataList = energyMapper.getDataList(queryForm);
            sumYear = sumDataList(yearDataList);

            // 本月数据总和
            queryForm.setStartTime(formatter.format(startOfMonthDateTime));
            queryForm.setEndTime(formatter.format(endOfMonthDateTime));
            List<Energy> monthDataList = energyMapper.getDataList(queryForm);
            sumMonth = sumDataList(monthDataList);

            // 昨天数据总和
            queryForm.setStartTime(formatter.format(startYesterday));
            queryForm.setEndTime(formatter.format(endYesterday));
            List<Energy> yesterdayDataList = energyMapper.getDataList(queryForm);
            sumYesterday = sumDataList(yesterdayDataList);
            map.put("gasSumYear", sumYear.divide(tenThousand, 3, BigDecimal.ROUND_HALF_UP));
            map.put("gasSumMonth", sumMonth.divide(tenThousand, 3, BigDecimal.ROUND_HALF_UP));
            map.put("gasSumYesterday", sumYesterday.divide(tenThousand, 3, BigDecimal.ROUND_HALF_UP));
        }

        return map;
    }

    @Override
    public Map<String, Object> getEnergyListByKb(QueryForm queryForm) throws Exception {
        List<Energy> waterList = getListByWater(queryForm);
        Map<String, Object> electricityList = getListByElectricity(queryForm);
        List<Energy> gasList = getListByGas(queryForm);
        Map<String, Object> allEnergyMap = new HashMap<>();
        allEnergyMap.put("waterList",waterList);
        allEnergyMap.put("electricityList",electricityList);
        allEnergyMap.put("gasList",gasList);
        return allEnergyMap;
    }

    private BigDecimal sumDataList(List<Energy> dataList) {
        BigDecimal sum = BigDecimal.ZERO;
        for (Energy energy : dataList) {
            try {
                String todayValue = energy.getToday();
                if (todayValue != null && !todayValue.isEmpty()) {
                    BigDecimal decimal = new BigDecimal(todayValue);
                    sum = sum.add(decimal);  // 正确累加
                }
            } catch (NumberFormatException e) {
                System.err.println("=====: " + energy.getToday());
            }
        }
        return sum;
    }
    public Map<String, Object> getWorkShopList(QueryForm queryForm) throws Exception {
        // 分隔符
        String delimiter = "园区";
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> energyTypesList = new ArrayList<>();
        Map<String, List<Map<String, Object>>> workShopMap = new HashMap<>();
        List<Energy> workshops = energyMapper.getElectricityType(queryForm.getEnergyType());
        for (Energy workshopEnergy : workshops) {
            Map<String, Object> totalData = new HashMap<>();
            String[] workshopParts = workshopEnergy.getWorkshop().split(delimiter, 2);
            if (workshopParts.length > 1) {
                totalData.put("area", workshopParts[1]);
            } else {
                totalData.put("area", workshopEnergy.getWorkshop());
            }
            // 使用 workShopMap 进行分组
            String workShop = workshopParts[0] + delimiter;
            if (!workShopMap.containsKey(workShop)) {
                workShopMap.put(workShop, new ArrayList<>());
            }
            if (!totalData.get("area").equals("")) {
                workShopMap.get(workShop).add(totalData);
            }
        }
        for (Map.Entry<String, List<Map<String, Object>>> entry : workShopMap.entrySet()) {
            Map<String, Object> workShopData = new HashMap<>();
            workShopData.put("workShop", entry.getKey());
            workShopData.put("list", entry.getValue());
            energyTypesList.add(workShopData);
        }
        result.put("energyTypes", energyTypesList);
        return result;
    }
    //水能
    @Scheduled(cron = "0 0/10 3 * * ?")
    public void addListByWater() {
        String httpurl = "http://58.242.198.147:82/prod-api/auth/masLogin";
        String username = "masSystem";
        String password = "mas123!@#";
        String accessToken = getAccessToken(httpurl, username, password);
        if (accessToken != null) {
            String Authorization = "Bearer " + accessToken;
            LocalDate now = LocalDate.now();
            LocalDate yesterday = now.minusDays(1);
            String currentYear = String.valueOf(yesterday.getYear()); // 使用昨天的年份
            String currentMonth = String.valueOf(yesterday.getMonthValue()); // 使用昨天的月份
            String dayOfMonth = "";
            if (now.getDayOfMonth() == 1) {
                // 如果今天是月份的第一天，那么昨天是上个月的最后一天
                dayOfMonth = String.valueOf(yesterday.lengthOfMonth());
            } else {
                // 如果不是月份的第一天，直接使用昨天的日份
                dayOfMonth = String.valueOf(yesterday.getDayOfMonth());
            }

            String dataUrl = "http://58.242.198.147:82/prod-api/energy/mas/getWaterData?dataDate=" + yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String response = doGet(dataUrl, Authorization);
            if (response != null) {
                List<DataItemVo> dataList = parseResponse(response);
                List<Energy> energyList = new ArrayList<>();
                for (DataItemVo item : dataList) {
                    EnergyExample example = new EnergyExample();
                    //水能
                    example.createCriteria().andEnergyTypeEqualTo("0").andRecordMonthEqualTo(currentMonth).andRecordYearEqualTo(currentYear).andRecordDayEqualTo(dayOfMonth);
                    int count = energyMapper.countByExample(example);
                    if (count == 0) {
                        Energy energy = new Energy();
                        String id = CommonUtil.generateRandomNum("energy-");
                        energy.setId(id);
                        energy.setWorkshop(item.getRoomName());
                        energy.setToday(item.getValue());
                        energy.setEnergyType("0");
                        energy.setUnit("t");
                        energy.setRecordMonth(currentMonth);
                        energy.setRecordYear(currentYear);
                        energy.setRecordDay(dayOfMonth);
                        energy.setCreateTime(new Date());
                        energy.setUpdateTime(new Date());
                        energyList.add(energy);
                    }
                }
                if (!energyList.isEmpty()) {
                    energyMapper.batchInsert(energyList);
                }
            }
        }
    }

    //电能
    @Scheduled(cron = "0 0/10 3 * * ?")
    public  void addListByElectricity(){
        String httpurl = "http://58.242.198.147:82/prod-api/auth/masLogin";
        String username = "masSystem";
        String password = "mas123!@#";
        String accessToken = getAccessToken(httpurl, username, password);
        if (accessToken != null) {
            String Authorization="Bearer "+accessToken;
            LocalDate now = LocalDate.now();
            LocalDate yesterday = now.minusDays(1);
            String currentYear = String.valueOf(yesterday.getYear()); // 使用昨天的年份
            String currentMonth = String.valueOf(yesterday.getMonthValue()); // 使用昨天的月份
            String dayOfMonth = "";
            if (now.getDayOfMonth() == 1) {
                // 如果今天是月份的第一天，那么昨天是上个月的最后一天
                dayOfMonth = String.valueOf(yesterday.lengthOfMonth());
            } else {
                // 如果不是月份的第一天，直接使用昨天的日份
                dayOfMonth = String.valueOf(yesterday.getDayOfMonth());
            }
            String dataUrl = "http://58.242.198.147:82/prod-api/energy/mas/queryElecData?dataDate=" + yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String response = doGet(dataUrl, Authorization);
            if (response != null) {
                List<DataItemVo> dataList = parseResponse(response);
                List<Energy> energyList = new ArrayList<>();
                for (DataItemVo item : dataList) {
                    EnergyExample example = new EnergyExample();
                    //电
                    example.createCriteria().andEnergyTypeEqualTo("1").andRecordMonthEqualTo(currentMonth).andRecordYearEqualTo(currentYear).andRecordDayEqualTo(dayOfMonth);
                    int count = energyMapper.countByExample(example);
                    if (count == 0){
                        Energy energy = new Energy();
                        String id = CommonUtil.generateRandomNum("energy-");
                        energy.setId(id);
                        energy.setWorkshop(item.getRoomName());
                        energy.setToday(item.getValue());
                        energy.setEnergyType("1");
                        energy.setUnit("kWh");
                        energy.setRecordMonth(currentMonth);
                        energy.setRecordYear(currentYear);
                        energy.setRecordDay(dayOfMonth);
                        energy.setCreateTime(new Date());
                        energy.setUpdateTime(new Date());
                        energyList.add(energy);
                    }
                }
                if (!energyList.isEmpty()) {
                    energyMapper.batchInsert(energyList);
                }
            }
        }

    }
    //气能
    @Scheduled(cron = "0 0/10 3 * * ?")
    public  void addListByGas(){
        String httpurl = "http://58.242.198.147:82/prod-api/auth/masLogin";
        String username = "masSystem";
        String password = "mas123!@#";
        String accessToken = getAccessToken(httpurl, username, password);
        if (accessToken != null) {
            String Authorization="Bearer "+accessToken;
            LocalDate now = LocalDate.now();
            LocalDate yesterday = now.minusDays(1);
            String currentYear = String.valueOf(yesterday.getYear()); // 使用昨天的年份
            String currentMonth = String.valueOf(yesterday.getMonthValue()); // 使用昨天的月份
            String dayOfMonth = "";
            if (now.getDayOfMonth() == 1) {
                // 如果今天是月份的第一天，那么昨天是上个月的最后一天
                dayOfMonth = String.valueOf(yesterday.lengthOfMonth());
            } else {
                // 如果不是月份的第一天，直接使用昨天的日份
                dayOfMonth = String.valueOf(yesterday.getDayOfMonth());
            }

            String dataUrl = "http://58.242.198.147:82/prod-api/energy/mas/getGasData?dataDate=" + yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String response = doGet(dataUrl, Authorization);
            if (response != null) {
                List<DataItemVo> dataList = parseResponse(response);
                List<Energy> energyList = new ArrayList<>();
                for (DataItemVo item : dataList) {
                    EnergyExample example = new EnergyExample();
                    //气能
                    example.createCriteria().andEnergyTypeEqualTo("2").andRecordMonthEqualTo(currentMonth).andRecordYearEqualTo(currentYear).andRecordDayEqualTo(dayOfMonth);
                    int count = energyMapper.countByExample(example);
                    if (count == 0){
                        Energy energy = new Energy();
                        String id = CommonUtil.generateRandomNum("energy-");
                        energy.setId(id);
                        energy.setWorkshop(item.getRoomName());
                        energy.setToday(item.getValue());
                        energy.setEnergyType("2");
                        energy.setUnit("m3");
                        energy.setRecordMonth(currentMonth);
                        energy.setRecordYear(currentYear);
                        energy.setRecordDay(dayOfMonth);
                        energy.setCreateTime(new Date());
                        energy.setUpdateTime(new Date());
                        energyList.add(energy);
                    }
                }
                if (!energyList.isEmpty()) {
                    energyMapper.batchInsert(energyList);
                }
            }
        }

    }

    //光能
    @Scheduled(cron = "0 0/10 3 * * ?")
    public  void addListByLight(){
        String httpurl = "http://58.242.198.147:82/prod-api/auth/masLogin";
        String username = "masSystem";
        String password = "mas123!@#";
        String accessToken = getAccessToken(httpurl, username, password);
        if (accessToken != null) {
            String Authorization="Bearer "+accessToken;
            LocalDate now = LocalDate.now();
            LocalDate yesterday = now.minusDays(1);
            String currentYear = String.valueOf(yesterday.getYear()); // 使用昨天的年份
            String currentMonth = String.valueOf(yesterday.getMonthValue()); // 使用昨天的月份
            String dayOfMonth = "";
            if (now.getDayOfMonth() == 1) {
                // 如果今天是月份的第一天，那么昨天是上个月的最后一天
                dayOfMonth = String.valueOf(yesterday.lengthOfMonth());
            } else {
                // 如果不是月份的第一天，直接使用昨天的日份
                dayOfMonth = String.valueOf(yesterday.getDayOfMonth());
            }

            String dataUrl = "http://58.242.198.147:82/prod-api/energy/mas/getLightData?dataDate=" + yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String response = doGet(dataUrl, Authorization);
            if (response != null) {
                List<DataItemVo1> dataList = parseResponse1(response);
                List<Energy> energyList = new ArrayList<>();
                for (DataItemVo1 item : dataList) {
                    EnergyExample example = new EnergyExample();
                    //光
                    example.createCriteria().andEnergyTypeEqualTo("3").andRecordMonthEqualTo(currentMonth).andRecordYearEqualTo(currentYear).andRecordDayEqualTo(dayOfMonth);
                    int count = energyMapper.countByExample(example);
                    if (count == 0){
                        Energy energy = new Energy();
                        String id = CommonUtil.generateRandomNum("energy-");
                        energy.setId(id);
                        energy.setWorkshop(item.getRoomName());
                        energy.setToday(item.getDvalue());
                        energy.setEnergyType("3");
                        energy.setUnit("kw.h");
                        energy.setRecordMonth(currentMonth);
                        energy.setRecordYear(currentYear);
                        energy.setRecordDay(dayOfMonth);
                        energy.setCreateTime(new Date());
                        energy.setUpdateTime(new Date());
                        energyList.add(energy);
                    }
                }
                if (!energyList.isEmpty()) {
                    energyMapper.batchInsert(energyList);
                }
            }
        }

    }


    public static String doPost(String httpurl, String jsonData) {
        HttpURLConnection connection = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null; // 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：post
            connection.setRequestMethod("POST");
            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(2000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 设置允许输出
            connection.setDoOutput(true);
            // 发送请求
            connection.connect();
            // 写入请求体
            os = connection.getOutputStream();
            os.write(jsonData.getBytes(StandardCharsets.UTF_8));
            os.flush();

            // 判断响应码
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // 通过connection连接，获取输入流
                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                }
                result = sbf.toString();
            } else {
                System.out.println("请求失败，HTTP 状态码：" + connection.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }

    public static String getAccessToken(String httpurl, String username, String password) {
        // 构造请求的 JSON 数据
        JSONObject json = new JSONObject();
        try {
            json.put("username", username);
            json.put("password", password);
        } catch (Exception e) {
            e.printStackTrace();
            return null; // 如果发生异常，返回 null
        }
        String jsonData = json.toString();

        // 发送 POST 请求
        String response = doPost(httpurl, jsonData);

        if (response != null && !response.isEmpty()) {
            JSONObject jsonResponse = JSONObject.parseObject(response);
            if (jsonResponse.containsKey("data")) {
                JSONObject data = jsonResponse.getJSONObject("data");
                return data.containsKey("access_token") ? data.getString("access_token") : null;
            }
        }
        return null;
    }

    public static String doGet(String httpurl, String authorization) {
        HttpURLConnection connection = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", authorization);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(60000);

            connection.connect();

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                }
                result = sbf.toString();
            } else {
                System.out.println("请求失败，HTTP 状态码：" + connection.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }

    public static List<DataItemVo> parseResponse(String response) {
        List<DataItemVo> dataList = new ArrayList<>();
        try {
            // 解析 JSON 响应
            JSONObject jsonResponse = JSONObject.parseObject(response);
            // 检查响应代码是否为 200
            if (jsonResponse.getInteger("code") == 200) {
                // 获取 data 数组
                JSONArray dataArray = jsonResponse.getJSONArray("data");
                // 遍历 data 数组
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject item = dataArray.getJSONObject(i);
                    String roomName = item.getString("roomName");
                    String value = item.getString("value");
                    // 创建 DataItemVo 对象并添加到列表中
                    dataList.add(new DataItemVo(roomName, value));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }

    //光伏特殊处理
    public static List<DataItemVo1> parseResponse1(String response) {
        List<DataItemVo1> dataList = new ArrayList<>();
        try {
            // 解析 JSON 响应
            JSONObject jsonResponse = JSONObject.parseObject(response);
            // 检查响应代码是否为 200
            if (jsonResponse.getInteger("code") == 200) {
                // 获取 data 数组
                JSONArray dataArray = jsonResponse.getJSONArray("data");
                // 遍历 data 数组
                for (int i = 0; i < dataArray.size(); i++) {
                    JSONObject item = dataArray.getJSONObject(i);
                    String roomName = item.getString("roomName");
                    String dValue = item.getString("dvalue");
                    String rvalue = item.getString("rvalue");
                    // 创建 DataItemVo 对象并添加到列表中
                    dataList.add(new DataItemVo1(roomName, dValue,rvalue));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }
}